package com.example.android.basicmediadecoder;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.common.media.AudioRecorderUtil;
import com.example.android.common.media.MediaCodecWrapper1;
import com.example.android.utils.AudioPlayError;
import com.example.android.utils.AudioPlayStatus;
import com.example.android.utils.AudioPlayStatusListener;
import com.example.android.utils.AudioPlayer;
import com.example.android.utils.EmptyAudioResult;
import com.example.android.utils.KCacheUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * @author lizhixian
 * @describe
 * @Version 1.0.0
 * @Created at 2019/2/22 15:13
 */
public class TestActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_READ_PHONE_STATE = 1000;
    Button btnRecord;
    Button btnPlay;
    Button btnAmr2Pcm;
    Button btnCopy;

    TextView tvRecordInfo;
    TextView tvChangeInfo;
    TextView tvChangeTime;
    MediaCodecWrapper1 mediaCodecWrapper;
    AudioPlayer mAudioPlayer;
    private AudioRecorderUtil mRecorderUtil;
    private String audioFilePath;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        btnRecord = findViewById(R.id.btnRecord);
        btnPlay = findViewById(R.id.btnPlay);
        btnAmr2Pcm = findViewById(R.id.btnAmr2Pcm);
        btnCopy = findViewById(R.id.btnCopy);

        btnRecord.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
        btnAmr2Pcm.setOnClickListener(this);
        btnCopy.setOnClickListener(this);

        tvRecordInfo = findViewById(R.id.tvRecordInfo);
        tvChangeInfo = findViewById(R.id.tv_result);
        tvChangeTime = findViewById(R.id.tv_time);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnRecord:
                checkReadPhoneState();
                break;
            case R.id.btnPlay:
                playAudio();
                break;
            case R.id.btnAmr2Pcm:
                startCovert();
                break;
            case R.id.btnCopy:
                copyFile();
                break;
        }
    }

    /**
     * 申请读取用户状态权限
     */
    void checkReadPhoneState() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //no current permission 说明1
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this, Manifest.permission.RECORD_AUDIO)) {
                //need explain
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_READ_PHONE_STATE);
            } else {
                //not need explain 说明2
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_READ_PHONE_STATE);
            }
        } else {
            //用于获取手机的did
            recordAudio();
        }
    }

    private void playAudio() {
        if (TextUtils.isEmpty(audioFilePath)) {
            makeToast("找不到音频文件，请先录音");
            return;
        }

        if (mAudioPlayer == null) {

            mAudioPlayer = new AudioPlayer();
            mAudioPlayer.setAudioPlayStatusListener(new AudioPlayStatusListener() {
                @Override
                public void audioPlayStatus(AudioPlayStatus status, String tag) {
                    if(status == AudioPlayStatus.STOPED){
                        playerComplete();
                    }
                }

                @Override
                public void onError(AudioPlayError error, String tag) {
                    playerComplete();
                }
            });
            mAudioPlayer.start(audioFilePath);
            btnPlay.setText("停止播放");
        }else {
            mAudioPlayer.stop();
            playerComplete();
        }
    }

    private void playerComplete() {
        mAudioPlayer = null;
        btnPlay.setText("开始播放");
    }

    private void startCovert() {
        if (TextUtils.isEmpty(audioFilePath)) {
            makeToast("找不到音频文件，请先录音");
            return;
        }
        Uri uri = Uri.parse(audioFilePath);
        try {

            mediaCodecWrapper = MediaCodecWrapper1.fromAudioUri(this, uri);
            mediaCodecWrapper.setCompleteSampleListener(new MediaCodecWrapper1.CompleteSampleListener() {
                @Override
                public void completeSample(final EmptyAudioResult result, final String content) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            SpannableStringBuilder builder = new SpannableStringBuilder(content);
//                            int indexOf = content.indexOf("的语音");
//                            builder.setSpan(new ImageSpan(TestActivity.this,result ? R.drawable.icon_right : R.drawable.icon_wrong),indexOf,indexOf + 3,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                            tvChangeInfo.setText(builder);

                            tvChangeTime.setText(content + "\n" + result.toString());

                            tvChangeInfo.setText("识别结果：" + (result.isValid() ? "有效" : "无效"));
                            tvChangeInfo.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,result.isValid() ? R.drawable.icon_right : R.drawable.icon_wrong,0);
                        }

                    });
            }});
            mediaCodecWrapper.startDecode();
            tvChangeInfo.setText("");
            tvChangeTime.setText("");
            tvChangeInfo.setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,0,0);
        } catch (IOException e) {
            e.printStackTrace();
            mediaCodecWrapper = null;
        }
    }

    private void copyFile() {
        if (TextUtils.isEmpty(audioFilePath)) {
            makeToast("找不到音频文件，请先录音");
            return;
        }
        FileInputStream inputStream;
        FileOutputStream outputStream;
        try {
            File excepDir = new File(KCacheUtils.getCacheDirectory() + "/exception/");
            if (!excepDir.exists()) {
                excepDir.mkdirs();
            }

            File inputFile = new File(audioFilePath);

            File excepFile = new File(excepDir, inputFile.getName());
            if (!excepFile.exists()) {
                excepDir.createNewFile();
            }
            inputStream = new FileInputStream(inputFile);
            outputStream = new FileOutputStream(excepFile);
            byte[] bytes = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            makeToast("记录成功！");
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inputStream = null;
            outputStream = null;
        }
    }

    private void recordAudio() {
        if (mRecorderUtil == null) {
            audioFilePath = null;
            mRecorderUtil = new AudioRecorderUtil();
            mRecorderUtil.setRecordEventListener(new AudioRecorderUtil.RecordEventListener() {
                @Override
                public void onFinishedRecord(String audioPath, int seconds) {
                    audioFilePath = audioPath;
                    tvRecordInfo.setText("录制时间：" + seconds + "\n" + "文件路径：" + audioPath);
                    btnRecord.setText("开始录制");
                }

                @Override
                public void onProgress(int seconds) {
                    tvRecordInfo.setText("录制时间：" + seconds);
                }

                @Override
                public void onStartRecord() {

                }
            });

            try {
                mRecorderUtil.startRecord();
                btnRecord.setText("停止录制");
                tvRecordInfo.setText("");
            } catch (IOException e) {
                e.printStackTrace();
                mRecorderUtil.setRecordEventListener(null);
                mRecorderUtil = null;
            }
        } else {
            mRecorderUtil.stopRecord();
            mRecorderUtil = null;
            btnRecord.setText("开始录制");
        }
    }

    private void makeToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_READ_PHONE_STATE: {
                //说明4
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //权限被授予，去做和当前权限相关的任务
                    recordAudio();
                    Log.e("AAAA", "onRequestPermissionsResult: 我做任务了");
                } else {
                    // permission denied, boo! Disable the 说明5
                    // functionality that depends on this permission.
                    makeToast("权限申请失败，请在设置中打开");
                }
                return;
            }

        }
    }
}
